
import React from 'react';

// Square函数组件
function Square(props) {
  return (
    <button className="square" onClick={() => props.onClick()}>
      {props.value}
    </button>
  )
}

class Board extends React.Component {
  renderSquare(i, r, c) {
    // return多行必须用()包裹起来
    // 在 React 中，有一个命名规范，通常会将代表事件的监听 prop 命名为 on[Event]，将处理事件的监听方法命名为 handle[Event] 这样的格式。
    return (
      <Square
        key={i + ''}
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i, r, c)}
      />
    )
  }
  // render 方法的返回值描述了你希望在屏幕上看到的内容。
  render() {
    const layout = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
    const eles = []
    layout.forEach((row, rowInx) => {
      const boards = []
      row.forEach((item, i) => boards.push(this.renderSquare(item, rowInx + 1, i + 1)))
      eles.push(<div className="board-row" key={rowInx + ''}>{boards}</div>)
    })
    return (
      <div>{eles}</div>
    )
  }
}

export class Game extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      history: [
        { squares: Array(9).fill(null), currentInx: [0, 0], selected: false }
      ],
      xIsNext: true,
      stepNumber: 0,
    }
  }

  handleClick(i, r, c) {
    console.log(i, r, c)
    const history = this.state.history.slice(0, this.state.stepNumber + 1)
    const current = history[history.length - 1]
    const squares = [...current.squares]
    const xIsNext = this.state.xIsNext
    if (calculateWinner(squares)) return
    squares[i] = xIsNext ? 'X' : 'O'
    // concat() 方法可能与你比较熟悉的 push() 方法不太一样，它并不会改变原数组，所以我们推荐使用 concat()。
    this.setState({
      history: history.concat([{ squares, currentInx: [r, c], selected: false }]), xIsNext: !xIsNext, stepNumber: history.length
    })
    console.log(squares)
  }

  descHistory() {
    let history = JSON.parse(JSON.stringify(this.state.history))
    const reveresArr = history.reverse()
    this.setState({
      history: reveresArr
    })
  }

  jumpTo(setp) {
    this.state.history.forEach(item => item.selected = false)
    const item = this.state.history.slice(setp, setp + 1)[0]
    item.selected = true

    this.setState({
      stepNumber: setp,
      xIsNext: setp % 2 === 0,
    })
  }

  updateHistory() {
    const history = this.state.history
    const move = history.map((move, setp) => {
      const desc = setp ? `go to move# ${setp} row: ${move.currentInx[0]} col: ${move.currentInx[1]}` : 'go to start'
      // 在游戏历史记录列表显示每一步棋的坐标，格式为 (列号, 行号)。
      return <li className={`history ${move.selected ? 'selected' : ''}`} key={setp + ''}><button onClick={() => this.jumpTo(setp)}>{desc}</button></li>
    })
    return move
  }

  render() {
    const history = this.state.history
    const current = history[this.state.stepNumber]
    const winner = calculateWinner(current.squares)
    let status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`
    if (winner) {
      status = 'Winner: ' + winner;
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={(i, r, c) => this.handleClick(i, r, c)}
          />
        </div>
        <div className="game-info">
          <button onClick={() => this.descHistory()}>desc</button>
          <div className="status">{status}</div>
          <ol>{this.updateHistory()}</ol>
        </div>
      </div>
    );
  }
}

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}